import { createRouter, createWebHashHistory } from 'vue-router'
import Login from '@/components/Login.vue'
import Home from '@/components/Home.vue'
import Welcome from '@/components/Welcome.vue'
import UserList from '@/components/admin/UserList.vue'
import PurchaseList from '@/components/admin/PurchaseList.vue'
import Warehouse from '@/components/admin/Warehouse.vue'

// 引入 NProgress（可选：页面加载进度条）
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: Login,
    meta: { title: '登录' }
  },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    meta: { requiresAuth: true },
    children: [
      {
        path: '/welcome',
        component: Welcome,
        meta: { title: '欢迎页', requiresAuth: true }
      },
      {
        path: '/user',
        component: UserList,
        meta: { title: '用户列表', requiresAuth: true }
      },
      {
        path: '/purchase',
        component: () => import('@/components/admin/PurchaseList.vue'),
        meta: { title: '采购列表', requiresAuth: true }
      },
      {
        path: '/warehouse',
        component: Warehouse,
        meta: { title: '仓库管理', requiresAuth: true }
      },
      {
        path: '/record',
        component: () => import('@/components/admin/InventoryRecord.vue'),
          meta: { title: '库存记录', requiresAuth: true }
      },
      {
        path: '/introduction',
        component: () => import('@/components/admin/Introduction.vue'),
        meta: { title: '农业资讯模块', requiresAuth: true }
      }

    ]
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  NProgress.start() // 开始进度条

  document.title = to.meta.title ? `${to.meta.title} - SportPlay` : 'SportPlay'

  if (to.path === '/login') return next()

  const userFlag = window.sessionStorage.getItem("user")
  if (!userFlag) return next('/login')

  next()
})

// 后置钩子（关闭进度条）
router.afterEach(() => {
  NProgress.done()
})

export default router